from rest_framework import views
from rest_framework.response import Response
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url


class CaptchaView(views.APIView):
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        new_key = CaptchaStore.pick()
        response_data = {
            'key': new_key,
            'image_url': request.build_absolute_uri(location=captcha_image_url(new_key)),
        }
        return Response({
            'message': '验证码获取成功',
            'data': response_data
        })





from django import forms
from django.shortcuts import render, HttpResponse


class UploadFileForm(forms.Form):
    file = forms.FileField()


def handle_uploaded_file(f):
    with open(f.name, 'wb') as destination:
        for chunk in f.chunks():
            destination.write(chunk)


def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponse('文件上传成功！')
    else:
        form = UploadFileForm()
    return render(request, 'upload.html', {'form': form})
